package com.tcenter.beans;

import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Component;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component("loginBean")
@Scope("request")
public class LoginBean {
	private String email = "ai@gmail.com";
    private String password = "ai123";


	public String loginAction() throws ServletException, IOException {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = ((HttpServletRequest)context.getRequest());
        HttpServletResponse response = ((HttpServletResponse)context.getResponse());
        RequestDispatcher dispatcher = request.getRequestDispatcher("/j_spring_security_check?j_username=" +
                                                                     email + "&j_password=" + password);
        dispatcher.forward(request, response);
        FacesContext.getCurrentInstance().responseComplete();
	    return "";
	}

    public void beforePhaseListener(final PhaseEvent phaseEvent) {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        Exception e = (Exception) context.getSessionMap().get(WebAttributes.AUTHENTICATION_EXCEPTION);
        if (e instanceof BadCredentialsException) {
            context.getSessionMap().put(WebAttributes.AUTHENTICATION_EXCEPTION, null);
            FacesMessage errorMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"Invalid email or password", null);
            FacesContext.getCurrentInstance().addMessage(null, errorMsg);
        }
    }

    public boolean isLogged() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String login = auth.getName();
        return ((login != null) && (!login.equalsIgnoreCase("anonymousUser")));
    }
	
	public String getEmail() {
		return this.email;
	}
	
	public void setEmail(String email) {
		this.email = email;
	}
	
	public String getPassword() {
		return this.password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}

}
